<template>
  <div>
    <el-tree
      ref="refTree"
      :data="permissionData"
      :props="{ label: 'name' }"
      default-expand-all
      :show-checkbox="true"
      :check-strictly="true"
      node-key="id"
    />
    <div style="display:flex;justify-content:flex-end ">
      <el-button type="primary" size="small" @click="submit">确定</el-button>
      <el-button size="small" @click="$emit('close')">取消</el-button>
    </div>
  </div>
</template>

<script>
// 根据id获取角色权限,保存分配的权限
import { getRoleDetail, assignPerm } from '@/api/settings'
// 获取权限列表
import { getPermissionList } from '@/api/permisson'
// 数据转化为树状图
import { tranListToTreeData } from '@/utils/index'
export default {
  props: {
    userId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      permissionData: [] // 存储权限数据
    }
  },
  created() {
    //   获取权限数据
    this.getPList()
  },
  methods: {
    // 获取权限数据
    async getPList() {
      try {
        // 获取全部权限列表
        const res = await getPermissionList()
        // console.log(res.data)
        this.permissionData = tranListToTreeData(res.data)

        // 获取当前角色的权限
        const info = await getRoleDetail(this.userId)
        // console.log(info.data)

        // 数据回填
        this.$refs.refTree.setCheckedKeys(info.data.permIds)
      } catch (err) {
        console.log(err)
        this.$message.error('获取权限列表失败')
      }
    },
    // 点击确定按钮
    async submit() {
      try {
        const permIds = this.$refs.refTree.getCheckedKeys()
        // console.log(permIds)
        await assignPerm({ id: this.userId, permIds })
        this.$message.success('保存成功')
        // 通知父组件关闭
        this.$emit('close')
      } catch (err) {
        console.log(err)
        this.$message.error('保存失败')
      }
    }
  }
}
</script>

<style scoped lang='less'>

</style>
